package com.usian.user.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.common.constants.message.FollowBehaviorConstants;
import com.usian.model.article.ApAuthor;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ApAuthorFeign.ArticleFeign;
import com.usian.user.mapper.ApUserFanMapper;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserRelationService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import groovy.util.logging.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Log4j2
@Transactional
public class UserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    private ArticleFeign articleFeign;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //参数检验
        if (dto.getOperation() == null || dto.getOperation()<0 || dto.getOperation()>1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getAuthorId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"作者ID不能为空");
        }
        //查找作者
        Integer followId = null;
        ApAuthor apAuthor = articleFeign.findByauthId(dto.getAuthorId());
        if (apAuthor !=null){
            followId =apAuthor.getId();
        }
        if (followId == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注的人为空");
        }else {
            ApUser user = AppThreadLocalUtils.getUser();
            if (user !=null){
                //关注(Operation 0:关注 1：取消关注)
                if (dto.getOperation()==0){
                    //关注
                  return followByUserId(user,followId,dto.getArticleId());
                }else {
                    //取消关注
                  return followCancelByUserId(user,followId);
                }
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            }
        }
    }

    @Autowired
    ApUserFanMapper apUserFanMapper;

    @Autowired
    ApUserFollowMapper apUserFollowMapper;

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    KafkaTemplate kafkaTemplate;
    //进行取消关注操作
    private ResponseResult followCancelByUserId(ApUser user, Integer followId) {
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, user.getId()).eq(ApUserFollow::getFollowId, followId));
        //判断用户是否关注
        if (apUserFollow != null){
            //检查用户是否有粉丝信息
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, user.getId()));
            if (apUserFan !=null){
                //删除用户粉丝信息
                apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, user.getId()));
            }
            //删除用户关注信息
            apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, user.getId()).eq(ApUserFollow::getFollowId, followId));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未关注");
        }
    }

    //进行关注操作
    private ResponseResult followByUserId(ApUser user, Integer followId, Long articleId) {
        ApUser apUser = apUserMapper.selectById(user.getId());
        ApUser apUser_auth = apUserMapper.selectById(followId);
        if (apUser == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"关注用户不存在");
        }
        //查找用户是否已经关注过了
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, followId));
        if (apUserFollow == null){
            //查找用户所关注的作者是否是用户的粉丝
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, apUser.getId()));
            if (apUserFan == null){
                //保存用户的粉丝信息
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(apUser.getId().longValue());
                apUserFan.setFansName(apUser.getName());
                apUserFan.setLevel((short)0);
                apUserFan.setIsDisplay(true);
                apUserFan.setIsShieldLetter(false);
                apUserFan.setIsShieldComment(false);
                apUserFan.setCreatedTime(new Date());
                apUserFanMapper.insert(apUserFan);
            }
            //保存用户所关注的信息
            apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(apUser.getId());
            apUserFollow.setFollowName(apUser_auth.getName());
            apUserFollow.setFollowId(followId);
            apUserFollow.setCreatedTime(new Date());
            apUserFollow.setIsNotice(true);
            apUserFollow.setLevel((short)1);
            apUserFollowMapper.insert(apUserFollow);
            // 记录关注行为
            FollowBehaviorDto dto = new FollowBehaviorDto();
            dto.setFollowId(followId);
            dto.setArticleId(articleId);
            dto.setUserId(apUser.getId());
            //异步发送消息，保存关注行为
            kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));
            return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已关注");
        }
    }
}
